package com.zrrd.learn.chapter08面向对象.pattern.myreflech;

/**
 * 狮子
 *
 * @author wrn
 * @version 1.0
 * @date 2023/8/7 15:35
 */

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * //1 使用反射实例化一个Lion子, 辛巴  红色
 * <p>
 * <p>
 * //1.1 LionFactory 里面有一个方法 public static Lion getLion(String name,String color){
 * // }
 */
public class LionFactory {


    public static Lion getLion(String name, String color) {

        Class<Lion> l1 = Lion.class;
        Lion mylion = null;
        try {
            mylion = l1.newInstance();

            Method setNameMethod = l1.getDeclaredMethod("setName", String.class);
            setNameMethod.invoke(mylion, name);

            Method setColorMethod = l1.getDeclaredMethod("setColor", String.class);
            setColorMethod.invoke(mylion, color);

        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return mylion;
    }

    public static Lion question0000(String name, String color) throws InstantiationException, IllegalAccessException, InvocationTargetException, IntrospectionException {
        Class c1 = Lion.class;
        Object obj = c1.newInstance();

        Field[] fields = c1.getDeclaredFields();
        for (Field field : fields) {
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), c1);
            Method getNameMethod = propertyDescriptor.getReadMethod();
            Method setNameMethod = propertyDescriptor.getWriteMethod();


            setNameMethod.invoke(obj, field.getName().equals("name") ? name : color);
        }

        return (Lion) obj;
    }

    public static void main(String[] args) {

        Lion l = LionFactory.getLion("辛巴","红色");
        System.out.println(l.getName());
        System.out.println(l.getColor());


    }

}
